﻿//Copyright © Omega Point 2008
//All rights reserved.
//This Software is Licensed under the New BSD License
//for a full copy of this license see http://www.codeplex.com/networkmessenger/license
//Redistributions of source code must retain the above copyright notice.
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Net.Sockets;
using OmegaPoint.Vista.Dwm;

namespace NetworkMessenger
{
    /// <summary>
    /// Interaction logic for ChatWindow.xaml
    /// </summary>
    public partial class ChatWindow : Window
    {
        public Guid ChatID;
        public string ToUser;
        public string FromUser;

        public ChatWindow(Guid chatID, string ChatUser)
        {
            InitializeComponent();            
            ChatID = chatID;
            ToUser = ChatUser;
            FromUser = Environment.UserName.ToLower() + "@" + Environment.MachineName.ToLower();
            Title = "Chat - " + ToUser;
            toSendTextBox.Clear();
            sendButton.IsEnabled = false;
            this.Activate();
        }
        public delegate void MessageDelegateMethod(Message msg);
        public void ShowMessage(Message msg)
        {
                MessageDelegateMethod theDelegateMethod = new MessageDelegateMethod(this.ShowMessageCurrentThread);
                this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,theDelegateMethod,(object)msg);  
        }
        public void ShowMessageCurrentThread(Message msg)
        {
            messagesTextBox.Text += msg.From + " says:\n" + msg.MessageBody + "\n\n";
            Tools.FlashWindow(new System.Windows.Interop.WindowInteropHelper(this).Handle, true);
            messagesTextBox.ScrollToEnd();
            System.Media.SystemSounds.Asterisk.Play();
        }
        private void SendMessage()
        {
            string toUser = ToUser.Split(new char[] { char.Parse("@") }, 2, StringSplitOptions.RemoveEmptyEntries)[0].ToLower();
            Message chatMsg = Message.Create(ChatID, toUser, FromUser, toSendTextBox.Text);
            System.Threading.Thread sendThread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(SendMessage));
            sendThread.Start(chatMsg);
        }
        private void SendMessage(object msg)
        {
            TcpClient cli = new TcpClient();
            try
            {
                System.Threading.Thread.BeginCriticalRegion();

                string toUser = ToUser.Split(new char[] { char.Parse("@") }, 2, StringSplitOptions.RemoveEmptyEntries)[0].ToLower();
                string toHost = ToUser.Split(new char[] { char.Parse("@") }, 2, StringSplitOptions.RemoveEmptyEntries)[1];
                cli = new TcpClient(toHost, Tools.GetPortFromName(toUser));
                cli.SendTimeout = 100;
             
                NetworkStream sendstream = cli.GetStream();
                byte[] buffer = ASCIIEncoding.Unicode.GetBytes(((Message)msg).ToXml());
                sendstream.Write(buffer, 0, buffer.Length);
                sendstream.Flush();
                sendstream.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("Error Sending Message\nPlease Check To Address and Try Again", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                System.Threading.Thread.EndCriticalRegion();
                cli.Close();
            }
        }

        private void sendButton_Click(object sender, RoutedEventArgs e)
        {
            SendMessage();
            messagesTextBox.Text += FromUser + " says:\n" + toSendTextBox.Text + "\n\n";
            messagesTextBox.ScrollToEnd();
            toSendTextBox.Clear();
        }

        private void toSendTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (toSendTextBox.Text.Replace(" ","").Length == 0)
            {
                sendButton.IsEnabled = false;
            }
            else
            {
                sendButton.IsEnabled = true;
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
             if (Aero.DoesOSSupportDwm() == true)
            {
                try
                {
                    Aero.ExtendGlassFrame(this, new Thickness(-1));
                }
                catch (Exception)
                {
                    //Alter Background to fill area
                    backgroundRectangle.RadiusX = 0;
                    backgroundRectangle.RadiusY = 0;
                    backgroundRectangle.Opacity = 1;
                }
            }
            else
            {
                backgroundRectangle.RadiusX = 0;
                backgroundRectangle.RadiusY = 0;
                backgroundRectangle.Opacity = 1;
            }        
        }
    }
}
